package messenger;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class MainWindow extends JFrame {
	private MessengerClient client = null;
	private MainWindow frame = null;
	private JList jl = new JList();
	public static final int WIDTH = 240;
	public static final int HEIGHT = 320;
	public static final int WAIT = 20000;
	private HashMap<String, ChatDialog> messengerMap = new HashMap<String, ChatDialog>();
	
	public MainWindow(MessengerClient c) {
		client = c;
		frame = this;
		
		setSize(WIDTH, HEIGHT);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setTitle("Messenger");
		
		JPanel panel = new JPanel();
		jl.setLayoutOrientation(JList.VERTICAL);
		jl.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount() >= 2) {
					String to = (String)((JList)e.getSource()).getSelectedValue();
					if(to != null && to.trim().length() >0) {
						ChatDialog messenger = new ChatDialog(client, frame, to);
						frame.addMessenger(to, messenger);
						messenger.setVisible(true);
					}
					
					
				}
			}
		});
		JScrollPane jsp = new JScrollPane(jl);
		jsp.setPreferredSize(new Dimension(200,250));
		panel.add(jsp, BorderLayout.CENTER);
		
		add(panel, BorderLayout.CENTER);
		
		ReceiveMessageDeamon deamon = new ReceiveMessageDeamon(this, client);
		deamon.start();
		
		Thread rf = new Thread() {
			@Override
			public void run() {
				while(true) {
					client.signalGetFriendList();
					try {
						sleep(WAIT);
					} catch (InterruptedException e) {
						
					}
				}
			}
		};
		rf.start();
		
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				super.windowClosing(e);
				client.disconnect();
				System.exit(0);
			}
		});
	}
	
	public void refreshFriendList(String[] friendArray) {
		jl.setListData(new String[0]);
		if(friendArray != null && friendArray.length > 0) {
			jl.setListData(friendArray);
		}
	}
	
	public void addMessenger(String toUser, ChatDialog m) {
		this.messengerMap.put(toUser, m);
	}
	
	public ChatDialog removeMessenger(String toUser) {
		return this.messengerMap.remove(toUser);
	}
	
	public ChatDialog getMessenger(String toUser) {
		return this.messengerMap.get(toUser);
	}
}


